# -*- coding: utf-8 -*-
from django.db import models
from django.contrib.auth.models import User
from django.contrib.sites.managers import CurrentSiteManager
from django.contrib.sites.models import Site
from django.db.models import permalink
from datetime import datetime

from django.contrib import comments
from django.contrib.comments.signals import comment_was_posted

class Post(models.Model):
	"""A blog post"""
	author = models.ForeignKey(User)
	pub_date = models.DateTimeField(default=datetime.now)
	title = models.CharField(max_length=100)
	slug = models.SlugField(
		unique_for_date='pub_date',
		max_length=255,
		help_text="Automatically built from the title. A slug is a short label generally used in URLs.",)
	intro = models.TextField(blank=True)
	text = models.TextField()
	enable_comments = models.BooleanField(default=True)
	sidebar = models.TextField(help_text="Sidebar content", blank=True)

	def __unicode__(self):
		return self.title

	class Meta:
		get_latest_by = 'pub_date'
		ordering      = ('-pub_date',)

	@models.permalink
	def get_absolute_url(self):
		return ('vwblogpost', (), { 'year': str(self.pub_date.year), 'slug': self.slug})


class Page(models.Model):
	"""A generic page"""
	title = models.CharField(max_length=200)
	intro = models.TextField(blank=True)
	text = models.TextField(help_text="Main content")
	sidebar = models.TextField(help_text="Sidebar content", blank=True)
	slug = models.SlugField(max_length=50, unique=True)
	page_keywords = models.CharField(max_length=255, blank=True)
	page_description = models.CharField(max_length=255, blank=True)
	updated = models.DateTimeField(auto_now=True)
	use_full_width = models.BooleanField(default=False)

	def __unicode__(self):
		return self.title

	@models.permalink
	def get_absolute_url(self):
		return ('vwpage', None, { 'slug': self.slug})




def on_comment_was_posted(sender, comment, request, *args, **kwargs):
	# Spam checking can be enabled/disabled per the comment's target Model
	# if comment.content_type.model_class() != Entry:
	#    return

	from django.contrib.sites.models import Site
	from django.conf import settings

	try:
		from akismet import Akismet
		from akismet import AkismetError
	except:
		return

	# use TypePad's AntiSpam if the key is specified in settings.py
	if hasattr(settings, 'TYPEPAD_ANTISPAM_API_KEY'):
		ak = Akismet(
				key=settings.TYPEPAD_ANTISPAM_API_KEY,
				blog_url='http://%s/' % Site.objects.get(pk=settings.SITE_ID).domain
				)
		ak.baseurl = 'api.antispam.typepad.com/1.1/'
	else:
		ak = Akismet(
				key=settings.AKISMET_API_KEY,
				blog_url='http://%s/' % Site.objects.get(pk=settings.SITE_ID).domain
				)

		try:
			key_ok = ak.verify_key()
		except AkismetError:
			return

		if key_ok:
			data = {
					'user_ip': request.META.get('REMOTE_ADDR', '127.0.0.1'),
					'user_agent': request.META.get('HTTP_USER_AGENT', ''),
					'referrer': request.META.get('HTTP_REFERER', ''),
					'comment_type': 'comment',
					'comment_author': comment.user_name.encode('utf-8'),
					}

			if ak.comment_check(comment.comment.encode('utf-8'), data=data, build_data=True):
				if hasattr(comment.content_object,'author'):
					user = comment.content_object.author
				else:
					from django.contrib.auth.models import User
					user = User.objects.filter(is_superuser=True)[0]
				comment.flags.create(user=user,	flag='spam')
				comment.is_public = False
				comment.save()

comment_was_posted.connect(on_comment_was_posted)
